# 菜单容器模块
from PyQt6.QtWidgets import QWidget, QTreeWidget, QTreeWidgetItem, QVBoxLayout
from PyQt6.QtCore import Qt, pyqtSignal
from typing import Dict, Optional
from parser.config_model import MenuItem, ConfigItem, CommentItem, ChoiceItem


class MenuTreeWidget(QTreeWidget):
    """菜单树控件"""

    configItemClicked = pyqtSignal(str)  # config_id

    def __init__(self, parent: Optional[QWidget] = None):
        super().__init__(parent)
        self.setHeaderLabels(["Menu"])
        self.setColumnWidth(0, 300)
        self.itemClicked.connect(self.on_item_clicked)

    def on_item_clicked(self, item: QTreeWidgetItem, column: int) -> None:
        """处理项目点击事件"""
        config_id = item.data(0, Qt.ItemDataRole.UserRole)
        if config_id:
            self.configItemClicked.emit(config_id)


class MenuModule:
    """菜单容器模块"""

    def __init__(self):
        self.menu_tree = MenuTreeWidget()
        self.menu_items: Dict[str, QTreeWidgetItem] = {}

    def create_menu_structure(self, menu_items: list[MenuItem]) -> QWidget:
        """创建菜单结构"""
        container = QWidget()
        layout = QVBoxLayout(container)
        layout.setContentsMargins(0, 0, 0, 0)

        self.menu_tree.clear()
        self.menu_items.clear()

        # 添加顶级菜单项
        for menu_item in menu_items:
            self.add_menu_item(menu_item, self.menu_tree.invisibleRootItem())

        layout.addWidget(self.menu_tree)
        return container

    def add_menu_item(
        self, menu_item: MenuItem, parent_item: QTreeWidgetItem
    ) -> QTreeWidgetItem:
        """添加菜单项"""
        tree_item = QTreeWidgetItem(parent_item)
        tree_item.setText(0, menu_item.prompt or menu_item.name or "Menu")
        tree_item.setData(0, Qt.ItemDataRole.UserRole, menu_item.id)
        tree_item.setExpanded(menu_item.is_expanded)

        # 添加子项
        for child in menu_item.children:
            if isinstance(child, MenuItem):
                self.add_menu_item(child, tree_item)
            elif isinstance(child, ConfigItem):
                config_item = QTreeWidgetItem(tree_item)
                config_item.setText(0, child.properties.prompt or child.name or "(config)")
                config_item.setData(0, Qt.ItemDataRole.UserRole, child.id)
                config_item.setData(0, Qt.ItemDataRole.UserRole + 1, "config")
            elif isinstance(child, CommentItem):
                comment_item = QTreeWidgetItem(tree_item)
                comment_item.setText(0, f"# {child.text}")
                comment_item.setForeground(0, Qt.GlobalColor.gray)
                comment_item.setData(0, Qt.ItemDataRole.UserRole + 1, "comment")
            elif isinstance(child, ChoiceItem):
                choice_item = QTreeWidgetItem(tree_item)
                choice_item.setText(0, f"choice: {child.prompt or 'Choice'}")
                choice_item.setData(0, Qt.ItemDataRole.UserRole, child.id)
                choice_item.setData(0, Qt.ItemDataRole.UserRole + 1, "choice")

        self.menu_items[menu_item.id] = tree_item
        return tree_item

    def toggle_menu(self, menu_id: str) -> None:
        """切换菜单展开状态"""
        menu_item = self.menu_items.get(menu_id)
        if menu_item:
            menu_item.setExpanded(not menu_item.isExpanded())

    def set_menu_expanded(self, menu_id: str, expanded: bool) -> None:
        """设置菜单展开状态"""
        menu_item = self.menu_items.get(menu_id)
        if menu_item:
            menu_item.setExpanded(expanded)

    def update_menu_visibility(self, menu_id: str, visible: bool) -> None:
        """更新菜单可见性"""
        menu_item = self.menu_items.get(menu_id)
        if menu_item:
            parent = menu_item.parent()
            if parent:
                index = parent.indexOfChild(menu_item)
                parent.setChildHidden(index, not visible)
